class Solution {
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    vector<vector<bool>> check1;
    vector<vector<bool>> check2;
    int row, col;
    vector<vector<int>>ret;
public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
        row = heights.size();
        col = heights[0].size();
        check1 = vector<vector<bool>>(row, vector<bool>(col, false));
        check2 = vector<vector<bool>>(row, vector<bool>(col, false));
        for (int j = 0; j < col; j++) {
            dfs(heights, 0, j, heights[0][j], check1);
            dfs(heights, row - 1, j, heights[row - 1][j], check2);
        }
        for (int i = 0; i < row; i++) {
            dfs(heights, i, 0, heights[i][0], check1);
            dfs(heights, i, col - 1, heights[i][col - 1], check2);
        }
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (check1[i][j] && check2[i][j])ret.push_back({ i,j });
            }
        }
        return ret;
    }
    void dfs(vector<vector<int>>& heights, int i, int j, int prev, vector<vector<bool>>& check) {
        check[i][j] = true;
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < row && y >= 0 && y < col && check[x][y] == false && heights[x][y] >= prev) {
                dfs(heights, x, y, heights[x][y], check);
            }
        }
    }
};